
from django.shortcuts import (get_object_or_404, redirect, render,
                              render_to_response)
from django.contrib.auth.models import User
from django.views.generic.list import ListView
from django.http import HttpResponse
from main import models,logic
import logging
import urllib
import json

logger = logging.getLogger('main')
# Create your views here.

class MainMuenListView(ListView):
    model = models.role
    template_name = 'main/index.html'

    def get_context_data(self, **kwargs):
        context = super(MainMuenListView, self).get_context_data(**kwargs)
        user_id=self.request.user.pk
        userinfo = models.user.objects.get(user_id=user_id)
        role = userinfo.role
        menu_id = str(role.rights).split(',')
        menulist = models.menu.objects.filter(id__in=menu_id).order_by("parent_id","order")
        
        menu_dict = logic.menu_struct(menulist)
        context['menu_dict'] = menu_dict
        logger.info("muen list struct complete")
        return context

def tab(request):
    return render(request, 'main/tab.html')

def demo(request):
    signature = request.GET.get("signature")
    timestamp = request.GET.get("timestamp")
    nonce = request.GET.get("nonce")
    echostr = request.GET.get("echostr")
    
    return HttpResponse(echostr)
from django.views.decorators.csrf import csrf_exempt
from weixin import receive,reply

@csrf_exempt
def demoPost(request):
    a = request.body
    
    recMsg = receive.parse_xml(a)
    if isinstance(recMsg, receive.Msg) and recMsg.MsgType == 'text':
        toUser = recMsg.FromUserName
        fromUser = recMsg.ToUserName
        content = "test"
        replyMsg = reply.TextMsg(toUser, fromUser, content)
        return HttpResponse(replyMsg.send())
    
    return HttpResponse("a")

import requests

def access_token(request):
    code = request.GET.get("code")
    state = request.GET.get("state")
    print code,state
    
    f = urllib.urlopen("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx1abc06e54fc73e79&secret=130674c83ffb8cda32c98bf69d53530e&code=%s&grant_type=authorization_code" % code)
    retVal = f.read()
    
    print retVal
    retJson = json.loads(retVal)
    
    if retJson.has_key('errcode'):
        print retJson['errcode']
        return HttpResponse(retVal)
    access_token = retJson['access_token']
    openid = retJson['openid']
    
    userinfoStr = urllib.urlopen("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN" % (access_token,openid))
    print userinfoStr.read()
    
    return HttpResponse(code)
